package com.kakame.netbook.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.kakame.netbook.common.constant.SysConstant;
import com.kakame.netbook.common.models.AuthUser;
import com.kakame.netbook.common.utils.AesUtil;
import com.kakame.netbook.common.utils.LoggerUtil;
import com.kakame.netbook.common.utils.PropUtil;

/**
 * 权限过滤器
 * @auth ex-hejm
 * @date 2018年11月20日 上午9:41:29
 */
public class AuthFilter implements Filter {
	
	private String includePage;
	private String excludePage;
	
	private String loginUrl;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		includePage = filterConfig.getInitParameter("includePage");
		excludePage = filterConfig.getInitParameter("excludePage");
		loginUrl = PropUtil.APP.get("app.loginUrl");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

//		String requestURI = request.getRequestURI();  // /recruit/admin/index.html
//		StringBuffer requestURL = request.getRequestURL();  // http://127.0.0.1:8080/recruit/admin/index.html
		String servletPath = request.getServletPath();  // /admin/index.html
//		String realPath = request.getServletContext().getRealPath("/");  // E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\recruit\
		
		boolean includePageMatch = false;
		boolean excludePageMatch = false;
		
		includePageMatch = judgePageIsAuth(servletPath, includePage);
		if(!includePageMatch){  // 如果没有在需要进行拦截的路径里，就放过
			chain.doFilter(request, response);
			return;
		}
		
		excludePageMatch = judgePageIsAuth(servletPath, excludePage);
		if(excludePageMatch){  // 如果在不需要进行拦截的路径里，就放过
			chain.doFilter(request, response);
			return;
		}
		
		
		AuthUser user = (AuthUser) request.getSession().getAttribute(SysConstant.SESSION_USER);
		if (user == null || null == user.getId()) {
			LoggerUtil.Logger.info("此页面需要登录后才能继续访问！");
			response.sendRedirect(loginUrl + "/" + AesUtil.fastEnCrypt(servletPath));
			return;
		}
		
		chain.doFilter(request, response);
	}

	/**
	 * 判断路径是否被拦截
	 * @auth ex-hejm
	 * @date 2018年11月20日 下午5:08:28
	 * @param servletPath
	 * @param authPage
	 * @return
	 */
	private boolean judgePageIsAuth(String servletPath, String authPage) {
		if(StringUtils.isBlank(authPage)) {
			return false;
		}
		boolean isMatch = false;
		String[] pages = authPage.split(",");
		for (String page : pages) {
			page = page.trim();
			if(page.endsWith("/*")) {  // 只匹配一级，如/admin/* -> /admin/index.html
				String afterPath = servletPath.replace(page.replace("/*", "/"), "");
				if(!StringUtils.equals(afterPath, servletPath) && afterPath.indexOf("/") == -1) {
					isMatch = true;
					break;
				}
				break;
			} else if(page.endsWith("/**")) {  // 匹配多级，如/admin/** -> /admin/index.html、/admin/sys/user/detail.html
				String afterPath = servletPath.replace(page.replace("/**", "/"), "");  // /admin/
				if(!StringUtils.equals(afterPath, servletPath)) {
					isMatch = true;
					break;
				}
			} else {  // 指定目录
				if(StringUtils.equals(page, servletPath)) {
					isMatch = true;
					break;
				}
			}
		}
		return isMatch;
	}

	@Override
	public void destroy() {

	}

}